#include <modules\input\win32\win32_input_interface.h>

namespace DelGE
{
	namespace Modules
	{
		namespace Input
		{
			Win32InputInterface::Win32InputInterface()
			{
				this->sName = "Win32 Input Interface";

				for (int i = 0; i < 3; i ++)
					this->eMouseState[i] = DelGE_KeyState_Up;

				for (int i = 0; i < 256; i ++)
					this->eKeyState[i] = DelGE_KeyState_Up;
			}

			Win32InputInterface::~Win32InputInterface()
			{
			}

			void Win32InputInterface::SetMousePosition(int iMouseX, int iMouseY)
			{
				SetCursorPos(iMouseX, iMouseY);

				//this->iMouseX = iMouseX;
				//this->iMouseY = iMouseY;
			}

			int Win32InputInterface::GetMouseX()
			{
				POINT mousePosition;

				GetCursorPos(&mousePosition);

				return mousePosition.x;
			}

			int Win32InputInterface::GetMouseY()
			{
				POINT mousePosition;

				GetCursorPos(&mousePosition);

				return mousePosition.y;
			}

			void Win32InputInterface::Update()
			{
				POINT mousePosition;

				GetCursorPos(&mousePosition);

				this->iMouseX = mousePosition.x;
				this->iMouseY = mousePosition.y;

				SHORT mouseState[3], keyState[256];

				mouseState[0] = GetAsyncKeyState(VK_LBUTTON);
				mouseState[1] = GetAsyncKeyState(VK_RBUTTON);
				mouseState[2] = GetAsyncKeyState(VK_MBUTTON);

				// Now we need to update the state for every key
				// The rules are:
				// * if the key is up and it is now down, make the key hit
				// * if the key was hit and it is still down, then the key is being held
				// * if the key was held or hit but is now up, then it has been pressed
				// * else the key is up.
				for (int i = 0; i < 3; i ++)
				{
					if (mouseState[i] & 0x8000) // down
					{
						if (this->eMouseState[i] == DelGE_KeyState_Hit)
							this->eMouseState[i] = DelGE_KeyState_Down;
						else if (this->eMouseState[i] == DelGE_KeyState_Up)
							this->eMouseState[i] = DelGE_KeyState_Hit;
					}
					else
					{
						if (this->eMouseState[i] == DelGE_KeyState_Down ||
							this->eMouseState[i] == DelGE_KeyState_Hit)
							this->eMouseState[i] = DelGE_KeyState_Pressed;
						else
							this->eMouseState[i] = DelGE_KeyState_Up;
					}
				}

				for (int i = 0; i < 256; i ++)
				{
					keyState[i] = GetAsyncKeyState(i);

					if (keyState[i] & 0x8000) // down
					{
						if (this->eKeyState[i] == DelGE_KeyState_Hit)
							this->eKeyState[i] = DelGE_KeyState_Down;
						else if (this->eKeyState[i] == DelGE_KeyState_Up)
							this->eKeyState[i] = DelGE_KeyState_Hit;
					}
					else
					{
						if (this->eKeyState[i] == DelGE_KeyState_Down ||
							this->eKeyState[i] == DelGE_KeyState_Hit)
							this->eKeyState[i] = DelGE_KeyState_Pressed;
						else
							this->eKeyState[i] = DelGE_KeyState_Up;
					}
				}
			}
		}
	}
}